package com.stone.framework.workflow.definition.handler.nodeevent;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.NodeEventHandler;
import com.bstek.uflo.process.node.Node;
import com.bstek.uflo.process.node.TaskNode;
import com.stone.framework.core.exception.BusinessException;

@Component
public class CompositeNodeEventHandler implements NodeEventHandler, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void enter(Node node, ProcessInstance processInstance, Context context) {
        if (!(node instanceof TaskNode)) {
            throw new BusinessException("CompositeNodeEventHandler只能配置在TaskNode");
        }
        ((TaskNode)node).getUserData().stream().filter(data -> data.getKey().startsWith("nodeEventHandler"))
            .map(data -> applicationContext.getBean(data.getValue(), NodeEventHandler.class))
            .forEach(handler -> handler.enter(node, processInstance, context));
    }

    @Override
    public void leave(Node node, ProcessInstance processInstance, Context context) {
        if (!(node instanceof TaskNode)) {
            throw new BusinessException("CompositeNodeEventHandler只能配置在TaskNode");
        }
        ((TaskNode)node).getUserData().stream().filter(data -> data.getKey().startsWith("nodeEventHandler"))
            .map(data -> applicationContext.getBean(data.getValue(), NodeEventHandler.class))
            .forEach(handler -> handler.leave(node, processInstance, context));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

    }

}
